package com.huluobo.a2307douyindemo.search

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.core.widget.addTextChangedListener
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.huluobo.a2307douyindemo.R
import com.huluobo.a2307douyindemo.adapter.SearchAdapter
import com.huluobo.a2307douyindemo.databinding.ActivitySearchBinding
import com.huluobo.lib_base.bean.SearchBean
import com.huluobo.lib_base.mvvm.BaseActivity
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class SearchActivity : BaseActivity<ActivitySearchBinding, SearchViewModel>() {
    private lateinit var searchAdapter: SearchAdapter
    override fun initData() {
        //发起搜索空白,产生全部的数据源
        vm.searchVideo("")
        //发起查询搜索记录
        vm.querySearch()

        vm.querySearchSuccess.observe(this) {
            searchAdapter.data.clear()
            searchAdapter.data.addAll(it)
            searchAdapter.notifyDataSetChanged()
        }

        vm.saveSearchSuccess.observe(this) {
            binding.searchEt.text.clear()
            vm.querySearch()
        }

        vm.deleteSearchSuccess.observe(this) {
            vm.querySearch()
        }
    }

    override fun initView() {
        val navHostFragment = supportFragmentManager.findFragmentById(R.id.fragmentContainerView) as NavHostFragment
        val navHostController = navHostFragment.navController
        binding.searchNav.setupWithNavController(navHostController)

        binding.searchBtn.setOnClickListener {
            if (binding.searchEt.text.isNotEmpty()) {
                vm.saveSearch(
                    SearchBean(keyword = binding.searchEt.text.toString())
                )
            }
        }

        binding.searchSaveRv.layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
        searchAdapter = SearchAdapter()
        binding.searchSaveRv.adapter = searchAdapter

        searchAdapter.addChildClickViewIds(R.id.item_search_delete_iv)
        searchAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.item_search_delete_iv -> {
                    vm.deleteSearch(
                        searchAdapter.data[position]
                    )
                }
            }
        }
    }
}